package generators;

import gamebackend.Block;

/**
 * Extends a block by one unit in every direction (including diagonal.)
 * @author Jonathan Caddey
 *
 */
public class EmbiggenGenerator extends AbstractGenerator {

	private final BlockRule my_rule;
	private boolean[] my_addedAbove;
	/**
	 * Whether the block at this index was added by this generator from the previous
	 * call to generate.
	 */
	private boolean[] my_previousAddedAbove;
	public EmbiggenGenerator(Block the_block, BlockRule the_rule) {
		super(the_block);
		my_rule = the_rule;
	}

	@Override
	public void generate(Block[][] blocks) {
		if (my_addedAbove == null) {
			my_addedAbove = new boolean[blocks[0].length];
			my_previousAddedAbove = new boolean[blocks[0].length];
		}
		boolean added_right = false;
		for (int col = 0; col < blocks[0].length; col++) {
			if (added_right) {
				added_right = false;
			} else if (blocks[1][col] == getBlock() && !my_previousAddedAbove[col]) {
				for (int c = col - 1; c <= col + 1; c++) {
					if (c >= 0 && c < blocks[0].length) {
						if (shouldReplace(blocks[2][c])) {
							my_addedAbove[c] = true;
							blocks[2][c] = getBlock();
						}
						if (shouldReplace(blocks[0][c])) {
							blocks[0][c] = getBlock();
						}
					}
				}
				if (col > 0 && shouldReplace(blocks[1][col - 1])) {
					blocks[1][col - 1] = getBlock();
				}
				if (col < blocks[0].length - 1 && shouldReplace(blocks[1][col + 1])) {
					blocks[1][col + 1] = getBlock();
					added_right = true;
				}
				
				
			}
		}
		boolean[] temp = my_previousAddedAbove;
		my_previousAddedAbove = my_addedAbove;
		my_addedAbove = temp;
		for (int col = 0; col < blocks[0].length; col++) {
			my_addedAbove[col] = false;
		}
		
	}
	private boolean shouldReplace(Block block) {
		return my_rule.test(block) && block != getBlock();
	}

}
